package com.hoongs.v1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoongs.v1.entity.LoginUser;
import com.hoongs.v1.entity.User;
import com.hoongs.v1.mapper.UserMapper;
import com.hoongs.v1.service.UserService;
import com.hoongs.v1.utils.JwtUtil;
import com.hoongs.v1.utils.PResult;
import com.hoongs.v1.utils.RedisUtil;
import com.hoongs.v1.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    public static final String NOT_FOUND_ARTICLE = "没有找到该用户！";

    @Resource
    private UserMapper userMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Result login(@RequestBody String username, @RequestBody String password, @RequestBody String code) {
        // authenticationManager实现用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authentication)) {
            // 认证不通过时抛出异常
            throw new RuntimeException("登录失败");
        }
        // 认证通过后，用userid生成jwt存入result中并返回
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId();

        String jwt = JwtUtil.createJWT(userId);
        redisUtil.setCacheObject("login:" + userId, loginUser);

        Map<String, Object> map = new HashMap<>();
        map.put("token", jwt);
        map.put("user", loginUser.getUser());


        return Result.opSuccess("登录成功", map);
    }

    @Override
    public Result logout() {
        // 获取 SecurityContextHolder 中的用户信息
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("无效token");
        }
        String userId = loginUser.getUser().getId();
        // 删除redis中的值
        redisUtil.deleteObject("login:" + userId);
        return Result.opSuccess("退出登录成功");
    }


    @Override
    public Result save(User user) {
        if (StringUtils.isNotBlank(user.getId())) {
            return this.update(user);
        } else {
            return this.add(user);
        }
    }

    @Override
    public Result add(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("username", user.getUsername());
        List<User> list = userMapper.selectList(wrapper);
        if (list.size() > 0) {
            return Result.opError("该用户名已被占用");
        }
        if (userMapper.insert(user) == 1) {
            return Result.opSuccess();
        } else {
            return Result.opError();
        }
    }

    @Override
    public Result remove(String id) {
        if (!findUserById(id)) return Result.opError(NOT_FOUND_ARTICLE);
        if (userMapper.deleteById(id) == 1) {
            return Result.opSuccess();
        } else {
            return Result.opError();
        }
    }

    @Override
    public Result update(User user) {
        if (!findUserById(user.getId())) return Result.opError(NOT_FOUND_ARTICLE);
        if (userMapper.updateById(user) == 1) {
            return Result.opSuccess();
        } else {
            return Result.opError();
        }
    }

    @Override
    public Result selectById(String id) {
        User user = userMapper.selectById(id);
        if (user == null) return Result.error(NOT_FOUND_ARTICLE);
        return Result.success(user);
    }

    @Override
    public Result selectList(String name) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.select("id", "username");
        if (StringUtils.isNotBlank(name)) {
            wrapper.like("username", name);
        }
        List<User> userList = userMapper.selectList(wrapper);
        return Result.success(userList);
    }

    @Override
    public Result selectPageList(Integer page, Integer size) {
        if (!checkPageQuery(page, size)) return Result.error("分页参数错误");

        Page<User> daoPage = new Page<>(page, size);
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.gt("status", 1);
        IPage<User> userDaoIPage = userMapper.selectPage(daoPage, wrapper);
        PResult rs = new PResult(userDaoIPage);
        return Result.success(rs);
    }

    /**
     * 根据Id查询用户是否存在
     */
    public Boolean findUserById(String id) {
        User user = userMapper.selectById(id);
        return user != null;
    }

    /**
     * 检查分页参数是否为空
     */
    public Boolean checkPageQuery(Integer page, Integer size) {
        return page != null && page > 0 && size != null && size > 0;
    }

}
